<template>
  <el-dialog title="添加"  :close-on-click-modal="false" :visible.sync="show" class="dialog_index dialog_banner site_fixed"
   :before-close="cancle">
   <el-form ref="form" v-loading="loading" class="agency_form scroll">
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane :label="item.site" :name="item.site" v-for="item  in formList" :key="item.id">
            <el-form-item label="Logo：" class="agencyLogo">
              <el-upload class="uploadAgency" :action="actionUrl" 
              :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item)"
                :on-error="handleError" :before-upload="beforeUpload"
              :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'agency', imageheight: imgH, imagewidth: imgW}" >
                <br><el-button size="small" type="primary" @click.stop="closeDrawerDialog">图库选择</el-button> 
                <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              </el-upload>
              <el-image :src="utils.setCdnUrl() +item.logo" v-show="item.logo"></el-image>
              <p class="upload__tip">建议上传.jpg/.jpeg/.png格式，且尺寸比例为1:1，大小≤1M，每次只能上传一个</p>
            </el-form-item>
            <el-form-item label="经销地：" >
              <el-input  :placeholder="'经销地('+item.site+')（必填项)'" v-model="item.dealership"></el-input>
            </el-form-item>
            <el-form-item label="公司：">
              <el-input  :placeholder="'公司('+item.site+')（必填项)'" v-model="item.company"></el-input>
            </el-form-item>
            <el-form-item label="地址：">
              <el-input :placeholder="'地址('+item.site+')（必填项)'" v-model="item.address"  ></el-input>
            </el-form-item>
            <el-form-item label="电话：" >
              <el-input :placeholder="'电话('+item.site+')（必填项)'" v-model="item.phone" ></el-input>
            </el-form-item>
            <el-form-item label="邮箱：" >
              <el-input :placeholder="'邮箱('+item.site+')（必填项)'" v-model="item.email" ></el-input>
            </el-form-item>
             <el-form-item label="官网：">
              <el-input :placeholder="'官网('+item.site+')（必填项)'" v-model="item.website" ></el-input>
            </el-form-item>

        </el-tab-pane>
      </el-tabs>
     
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" :loading="is_submit" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="'agency'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

   </el-dialog>
</template>

<script>
import { siteListGet } from '@/api/manage/site.js'
import { extendObj } from '@/utils/index'
import { add } from '@/api/product/agency.js'
import Drawer  from '@/components/Gallery/index.vue' 
export default {
  data () {
    return {
      formList:[],
      loading: false,
      activeName: '',
      is_submit : false,
      showDrawer: false,
      actionUrl: "/api/api/general/upload",
      imgW: '',
      imgH: ''
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
  },
  components: { Drawer },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.getSite()
      }
    }
  },
  methods: {
        // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if(data && data.filePathNameHttp )  { 
        for(let i =0; i< this.formList.length; i++){
          this.formList[i].logo = data.filePathName
        }
        
      }
    },
    handleSuccess(response){
      for(let i =0; i< this.formList.length; i++){
        this.formList[i].logo = response.data.filePathName
      }
      this.$message.success('上传LOGO成功')   
    },
    handleError(){
      this.$message.error('上传LOGO失败')   
    },
    beforeUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg'){
        this.$message.error("仅支持.jpg/.jpeg/png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width ==  img.height ;
          valid ? resolve() : reject();
          that.imgW = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        that.$message.error('上传图标为正方形')
        return Promise.reject()
      })
      return isSize
    },
    getSite (){
      siteListGet().then(res=>{
        if (res.status == 200) {
          let data = res.data
          for(let i = 0; i < data.length; i++){
            let obj = {
              website: '',
              email: '',
              phone: '',
              address: '',
              company: '',
              dealership: '',
              logo: ''
            }
            extendObj(data[i], obj)
            data[i].site_id = data[i].id
            if (i == 0){
              this.activeName= data[i].site
            } 
          }
          this.formList= data
          this.loading = false
        }

      })
    },
    submitForm () {
      let status = this.validateForm()
      if(status && !this.is_submit){
        this.add()
      }
    },
    add () {
      let list = this.formList

      let params = {
        data: JSON.stringify(list) 
      }
      this.is_submit = true
      add(params).then(res => {
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
        this.is_submit = false
      })
    },
    validateForm () {
      let list = this.formList

      let status = true
      for ( let i = 0; i < list.length; i++ ){
        if (list[i].logo === '') {
          this.$message.error('站点' + list[i].site + 'Logo为必填项')
          status = false
          break
        }
        if (list[i].dealership === '') {
          this.$message.error('站点' + list[i].site + '经销地为必填项')
          status = false
          break
        }

        if (list[i].company === '') {
          this.$message.error('站点' + list[i].site + '公司为必填项')
          status = false
          break
        }
        if (list[i].address === '') {
          this.$message.error('站点' + list[i].site + '地址为必填项')
          status = false
          break
        }
         if (list[i].phone === '') {
          this.$message.error('站点' + list[i].site + '电话为必填项')
          status = false
          break
        }
        if (list[i].email === '') {
          this.$message.error('站点' + list[i].site + '邮箱为必填项')
          status = false
          break
        }
         if (list[i].website === '') {
          this.$message.error('站点' + list[i].site + '官网为必填项')
          status = false
          break
        }
      }
      return status
    },
    
    cancle(){
      this.$refs.form.resetFields(); // 清空原来的数据
      this.$emit('closeDialog')
    },
  },
 
}
</script>

<style lang="scss">

</style>